import mongoose from "mongoose";
import connectToDatabase from "./db";
import WordCloud, { WordCloudType } from "../models/wordCloud";

class WordService {
    /**
     * 确保 MongoDB 连接已建立
     */
    private static async connect() {
        if (mongoose.connection.readyState === 0) {
            await connectToDatabase();
        }
    }

    // 创建、添加
    static async createWord(
        id: string,
        word: { en: string; zh: string },
    ): Promise<WordCloudType> {
        await this.connect();

        let userWord = await WordCloud.findOne({ user_id: id });

        if (!userWord) {
            userWord = await WordCloud.create({
                user_id: id,
                wordList: [{ ...word, value: 1 }],
            });
        } else {
            const index = userWord.wordList.findIndex(
                (w: { en: string }) => w.en == word.en
            );

            if (index !== -1) {
                userWord.wordList[index].value += 1;
                userWord.markModified('wordList');
            } else {
                userWord.wordList.push({ ...word, value: 1 });
            }
        }

        await userWord.save();

        return userWord;
    }


    //用户id查找
    static async findUser(
        id: string,
    ): Promise<WordCloudType | null> {
        await this.connect();

        const userWord = await WordCloud.findOne({ user_id: id });

        if (userWord) {
            return userWord
        } else {
            return null
        }

    }
}

export default WordService;
